package com.zcsy.manage.web.mall;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.ShopCategory;
import com.zcsy.manage.model.mall.CategoryAttr;
import com.zcsy.manage.model.mall.CategoryAttrValue;
import com.zcsy.manage.model.mall.GoodsCategory;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopCategoryService;
import com.zcsy.manage.service.mall.ICategoryAttrService;
import com.zcsy.manage.service.mall.IGoodsCategoryService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;


/**
 * @Title: GoodsCategoryController.java
 * @Package： com.zcsy.manage.web.mall 
 * @Description: 商品分类管理及改分类的属性管理
 * @author caiyinli 13277030520@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月15日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/goodsCategory")
public class GoodsCategoryController {
	
	@Autowired 
	private IGoodsCategoryService goodsCategoryService;
	
	@Autowired 
	private ICategoryAttrService categoryAttrService;
	
	@Autowired 
	private IDictService dictService;
	
	@Autowired
	private IShopCategoryService shopCategoryService;

	private static final int SECOND_LEVEL = 2;  //商品分类等级为2
	private static final int FIRST_LEVEL  = 1;  //商品分类等级为1
	/**
	 * @Description 返回商品分类页面<br>
	 * @param model
	 * @param req 用户请求
	 * @return 返回商品分类页面
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年4月15日
	 * @see 
	 */
	@RequestMapping(value="categoryList" , method = RequestMethod.GET)
	public String categoryList(Model model, HttpServletRequest req){
		
		return "mall/goodsCategory/goodsCategoryList";
	}
	

    /**
     * @Description 生成商品分类树<br>
     * @param req 用户请求
     * @param response
     * @return 返回商品分类json字符串
     *         {"id":分类id,"pId":分类上级id,"name":分类名称}
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="categoryTree" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson treeData(HttpServletRequest req,HttpServletResponse response){
        RequestJson result = new RequestJson();
        JSONArray jsonArr=new JSONArray();
        try {
            List<GoodsCategory> list = goodsCategoryService.getAllGoodsCategory();
            for(GoodsCategory item : list){
            	JSONObject json = new JSONObject();
            	json.put("id", item.getId());
            	json.put("pId", item.getParentId());
            	json.put("name", item.getName());
            	jsonArr.add(json);
            }
            result.setObj(jsonArr.toJSONString());
            System.out.println(jsonArr.toJSONString());
        }catch (Exception e) {
           result.setMsg("操作异常");
           result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * @Description 返回商品分类新增和编辑页面<br>
     * 1、id不为空不为0，返回编辑页面
     * 2、否则，返回新增页面
     * @param model
     * @param id 商品分类id
     * @return 返回商品分类新增和编辑页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value = "categoryEdit", method = RequestMethod.GET)
    public String categoryEdit(Model model, String id) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
                GoodsCategory goodsCategory = new GoodsCategory();
                goodsCategory.setLevel(-1);
                goodsCategory.setIsNeedConfrim(1);
                model.addAttribute("goodsCategory",goodsCategory);
            } else {
            	GoodsCategory goodsCategory = goodsCategoryService.getGoodsCategoryById(id);
                model.addAttribute("goodsCategory", goodsCategory);
                GoodsCategory gInfo = goodsCategoryService.getGoodsCategoryById(goodsCategory.getParentId());
                model.addAttribute("gInfo", gInfo);
                List<GoodsCategory> list = new ArrayList<GoodsCategory>();
                if(goodsCategory.getLevel() == SECOND_LEVEL){
                	list = goodsCategoryService.getGoodsCategoryByLevel(FIRST_LEVEL);
                }
                model.addAttribute("goodsList", list);
                model.addAttribute("type", Constants.EDIT_TYPE);
            }
            
        } catch (Exception e) {
        }
        return "mall/goodsCategory/goodsCategoryEdit";
    }
    
	/**
	 * @Description 通过等级获取该等级的所有商品分类<br>
	 * @param level 分类等级
	 * @param req 用户请求
	 * @return 返回商品分类集合
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年4月15日
	 * @see 
	 */
	@RequestMapping(value="/goodsCategoryByLevel" , method = RequestMethod.POST)
	@ResponseBody
    public List<GoodsCategory> goodsCategoryByLevel( int level, HttpServletRequest req){
	    List<GoodsCategory> list = goodsCategoryService.getGoodsCategoryByLevel(level);
	    return list;
    }
	
	@RequestMapping(value="/shopCategoryByLevel" , method = RequestMethod.POST)
    @ResponseBody
    public List<ShopCategory> shopCategoryByLevel(HttpServletRequest req){
        List<ShopCategory> list = shopCategoryService.getParentBylevel(Constants.INT_ONE);
        return list;
    }
    
	/**
	 * @Description 通过主键id获取商品分类对象<br>
	 * @param id 主键id
	 * @param model
	 * @param req 用户请求
	 * @return 返回该商品分类对象
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年4月15日
	 * @see 
	 */
	@RequestMapping(value="categoryDetail" , method = RequestMethod.GET)
	@ResponseBody
	public GoodsCategory categoryDetail(String id,Model model, HttpServletRequest req){
		
		GoodsCategory goodsCategory = goodsCategoryService.getGoodsCategoryById(id);
		
		//判断该分类节点是否是叶子节点
		goodsCategory.setLeaf(goodsCategoryService.isLeaf(id));
		
		return goodsCategory;
	}
	
    
    /**
     * @Description 保存或更新方法<br>
     * 1、id不为空且不为0，表示更新
     * 2、否则，表示新增
     * @param req 用户请求
     * @param name 分类名称
     * @param descrip 分类描述
     * @param level 分类等级
     * @param pid 上级分类id
     * @param id 主键id
     * @param distribute 是否需要配送1：是 0：否，默认否
     * @param servicePrice 是否需要平台服务费 1：是  0：否 ，默认否
     * @param confirm 是否需要商家确认 1：是 0：否 ，默认是
     * @return 返回1：成功  0：失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="/saveOrUpdateGoodsCategory" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateGoodsCategory(HttpServletRequest req,String name,String descrip,
    				Integer level,String pid,String id,int distribute,int servicePrice,int confirm){
    	
		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		try {
			GoodsCategory goodsCategory = new GoodsCategory();
			goodsCategory.setName(name);
			goodsCategory.setDescrip(descrip);
			goodsCategory.setLevel(level);
			goodsCategory.setParentId(pid);
			goodsCategory.setIsNeedDistribute(distribute);
			goodsCategory.setIsServicePrice(servicePrice);
			goodsCategory.setIsNeedConfrim(confirm);
			int flag = 0;
			if(id != null && !"0".equals(id)){
				goodsCategory.setId(id);
				flag = goodsCategoryService.update(goodsCategory);
				if(flag == Constants.SQL_RESULT_SUCCESS){
					result.setSuccess(true);
					LogUtils.insertLog("用户编辑商品分类信息", user.getId(), req);

				}
			}else{
				goodsCategory.setId(UniqueNumberUtils.get18UniqueNumber());
				flag = Constants.SQL_RESULT_ERROR;
				flag = goodsCategoryService.insert(goodsCategory);
				if(flag == Constants.SQL_RESULT_SUCCESS){
					result.setSuccess(true);
					LogUtils.insertLog("用户新增商品分类信息", user.getId(), req);

				}
			}
			
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMsg("操作异常");
		}
        return result;
    }
    
    /**
     * @Description 删除商品分类<br>
     * @param req 用户请求
     * @param id 主键id
     * @return 返回1：成功  0：失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="/delGoodsCategory" , method = RequestMethod.GET)
    @ResponseBody
    public RequestJson delGoodsCategory( HttpServletRequest req,String id){
		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		try {
             List<GoodsCategory> list = goodsCategoryService.getGoodsCategoryByParentId(id);
			if(CollectionUtils.isEmpty(list)){
				int flag = goodsCategoryService.deleteByPrimaryKey(id);
				if(flag == 1){
					result.setSuccess(true);
					LogUtils.insertLog("用户删除商品分类信息", user.getId(), req);

				}
			}else{
				result.setMsg("该组织下存在下级组织，请先删除下级!");
				result.setSuccess(false);
				LogUtils.insertLog("用户删除商品分类信息", user.getId(), req);
			}
			
		} catch (Exception e) {
			result.setMsg("操作异常");
			result.setSuccess(false);
		}
        return result;
    }
    

    /**
     * @Description 根据分类id获取分类属性<br>
     * @param model
     * @param categoryId 分类id
     * @param req 用户请求
     * @return 返回分类属性集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="categoryAttrList" , method = RequestMethod.GET)
    public String categoryAttrList(Model model, String categoryId, HttpServletRequest req){
        
    	List<CategoryAttr> categoryAttrList = categoryAttrService.selectByCategoryId(categoryId);
    	model.addAttribute("categoryAttrList", categoryAttrList);
    	model.addAttribute("categoryId", categoryId);
        
        return "mall/goodsCategory/categoryAttrList";
    }
    
    /**
     * @Description 跳转属性新增或编辑页面<br>
     * @param model
     * @param id 属性主键id
     * @return 返回属性新增或编辑页面
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value = "categoryAttrEdit", method = RequestMethod.GET)
    public String categoryAttrEdit(Model model, String id,String categoryId) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id) && categoryId != "") {
                model.addAttribute("type", Constants.MENU_STATE_ENABLED);
                CategoryAttr categoryAttr = new CategoryAttr();
                model.addAttribute("categoryAttr",categoryAttr);
            } else {
            	CategoryAttr categoryAttr = categoryAttrService.selectCategoryAttrById(id);
                model.addAttribute("categoryAttr", categoryAttr);
                model.addAttribute("type", Constants.MENU_STATE_DISABLED);
            }
            
            GoodsCategory goodsCategory = goodsCategoryService.getGoodsCategoryById(categoryId);
            model.addAttribute("secondName", goodsCategory.getName());
            model.addAttribute("firstName", goodsCategory.getParentName());
            model.addAttribute("categoryId", categoryId);
            
            List<Dict> inputTypes = dictService.getDictFromCache("inputType");
            model.addAttribute("inputTypes", inputTypes);

            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "mall/goodsCategory/categoryAttrEdit";
    }
    
    /**
     * @Description 保存或更新属性方法<br>
     * 1、id不为空且不为0，表示更新
     * 2、否则，表示新增
     * @param req 用户请求
     * @param name 属性名称
     * @param categoryId商品分类id
     * @param attrId 属性id
     * @return 1:成功 0：失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="/saveOrUpdateAttr" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateAttr(HttpServletRequest req,String name,String categoryId,String attrId,int inputType){
    	
		RequestJson result = new RequestJson();
		try {
			User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
			CategoryAttr record = new CategoryAttr();
			record.setName(name);
			record.setCategoryId(categoryId);
			record.setUserAccount(user.getLoginname());
			record.setInputType(inputType);
			int flag = 0;
			if(attrId != null && !"0".equals(attrId)){
				record.setId(attrId);
				record.setUpdateTime(new Date());
				flag = categoryAttrService.update(record);
				if(flag == Constants.SQL_RESULT_SUCCESS){
					result.setSuccess(true);
					LogUtils.insertLog("用户编辑商品分类属性", user.getId(), req);

				}
			}else{
				record.setId(UniqueNumberUtils.get18UniqueNumber());
				record.setSendTime(new Date());
				flag = Constants.SQL_RESULT_ERROR;
				flag = categoryAttrService.insert(record);
				if(flag == Constants.SQL_RESULT_SUCCESS){
					result.setSuccess(true);
					LogUtils.insertLog("用户新增商品属性", user.getId(), req);

				}
			}
			
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMsg("操作异常");
		}
        return result;
    }
    
    /**
     * @Description 批量删除分类属性<br>
     * 备注：删除之前判断被删除属性的属性值时候被商品所使用（暂时还没做）
     * @param attrIDs 需要被删除的属性id集合
     * @param req 用户请求
     * @return 1：成功  0：失败
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value = "deleteAttr", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteAttr(String attrIDs,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

        try {
			String ids[] = attrIDs.split("\\,");
			for (int i = 0; i < ids.length; i++ ) {
				categoryAttrService.deleteByPrimaryKey(ids[i]);
			}
			result.setSuccess(true);
			LogUtils.insertLog("用户删除商品分类信息", user.getId(), req);

		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        return result;
}
    
    @RequestMapping(value = "attrValueEdit", method = RequestMethod.GET)
    public String attrValueEdit(Model model, String id) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.MENU_STATE_ENABLED);
                CategoryAttrValue attrValue = new CategoryAttrValue();
                model.addAttribute("attrValue",attrValue);
            } else {
            	List<CategoryAttrValue> attrValue = categoryAttrService.selectByAttrId(id);
                model.addAttribute("attrValue", attrValue);
                model.addAttribute("attrValueSize", attrValue.size());
                
                CategoryAttr categoryAttr = categoryAttrService.selectCategoryAttrById(id);
                model.addAttribute("attrName", categoryAttr.getName());
                model.addAttribute("attrId", id);
                model.addAttribute("type", Constants.MENU_STATE_DISABLED);
                
            }
            
        } catch (Exception e) {
        }
        return "mall/goodsCategory/attrValueEdit";
    }
    
    @RequestMapping(value="/saveOrUpdateAttrValue" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateAttrValue(HttpServletRequest req,String values,String attrId){
    	
		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		JSONArray jsonArray = JSONObject.parseArray(values);
		try {
			//保存之前清除该属性的所有属性值
			categoryAttrService.deleteValueByAttrId(attrId);
            if(jsonArray != null && jsonArray.size() >0){
                for(int i = 0;i<jsonArray.size();i++){
                	JSONObject object = jsonArray.getJSONObject(i);
                	
                     CategoryAttrValue record = new CategoryAttrValue();
                     record.setId(UniqueNumberUtils.get18UniqueNumber());
                     record.setName(object.getString("name"));
                     record.setGoodsAttrId(attrId);
                     
                     categoryAttrService.insertAttrValue(record);
                     
                }
            }
			result.setSuccess(true);
			LogUtils.insertLog("用户新增商品属性值", user.getId(), req);

		} catch (Exception e) {
			result.setSuccess(false);
			result.setMsg("操作异常");
		}
        return result;
    }
    
    /**
     * @Description 根据上级分类id获取其所有下级分类集合<br>
     * @param parentId 上级分类id
     * @param req 用户请求
     * @return 当前分类的所有下级分类集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月26日
     * @see 
     */
    @RequestMapping(value="/getCategoryByParentId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getCategoryByParentId(String parentId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<GoodsCategory> goodsCategories = goodsCategoryService.getGoodsCategoryByParentId(parentId);
    		result.setObj(goodsCategories);
    	} catch (Exception e) {
    	}
    	return result;
    }
}
